<?php
/**
 * ProjektMan
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @category   ProjektMan
 * @name       IndexController.php
 * @license    LICENSE.txt     New BSD License
 */

/**
 * Error page is displayed when there is an exception in the code
 *
 * @category   ProjektMan
 * @name       IndexController
 * @license    LICENSE.txt     New BSD License
 */
class IndexController extends Projekt_Action
{
    /**
     * Default index action shows login form and redirect on successful authentication
     *
     */
    public function indexAction ()
    {
        $form = new Zend_Form();
        $form->setAction('/')->setMethod('post');
        
        // Create and configure username element:
        $username = $form->createElement('text', 'username');
        $username->setLabel('Username')->addValidator('alnum')->addValidator('regex', false, array(
            '/^[a-z]+/'
        ))->setRequired(true)->addFilter('StringToLower');
        
        // Create and configure password element:
        $password = $form->createElement('password', 'password');
        $password->setLabel('Password')->setRequired(true);
        
        // Add elements to form:
        $form->addElement($username)->addElement($password)->// use addElement() as a factory to create 'Login' button:
        addElement('submit', 'login', array(
            'label' => 'Login'
        ));

        //process the form if it has been submitted
        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            if ($form->isValid($formData)) {
                $userId = User::getUserId($formData['username'], $formData['password']);
                if (isset($userId)) {
                    session_start();
                    $_SESSION['user_id'] = $userId;
                    $_SESSION['username'] = $formData['username'];
                    $this->_redirect('/project/list/');
                } else {
                    $this->_redirect('/?error=login');
                }
            } else {
                $form->populate($formData);
            }
        }
        
        $this->view->form = $form;
    }
}